package com.djl.handler;
import com.djl.annotation.OpenFeign;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.client.RestTemplate;

import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;

/**
 * 代理类的回调方法,所有操作在此进行
 */
public class DefaultHandler implements InvocationHandler {

    private BeanFactory beanFactory;

    public DefaultHandler(BeanFactory beanFactory){
        this.beanFactory = beanFactory;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // Object 方法，走原生方法,比如hashCode()
        if (Object.class.equals(method.getDeclaringClass())) {
            return method.invoke(this,args);
        }
        OpenFeign annotation = method.getDeclaringClass().getAnnotation(OpenFeign.class);
        //执行代理类的方法
        return invokeMethod(annotation,method,args);
    }

    /**
     * 处理具体业务逻辑
     */
    private Object invokeMethod(OpenFeign annotation, Method method,Object[] args) {
        Object object = null;
        try {
            //获取注解上服务名称
            String serverName = annotation.serverName();
            DiscoveryClient discoveryClient = beanFactory.getBean(DiscoveryClient.class);

            //根据服务名拉取改服务名下实例对象
            List<ServiceInstance> instances = discoveryClient.getInstances(serverName);

            Annotation[] annotations = method.getAnnotations();
            for (Annotation annotation1 :annotations) {
                //判断请求方式
                if(annotation1 instanceof PostMapping){
                    //post请求
                    PostMapping post = method.getAnnotation(PostMapping.class);
                    String[] value = post.value();
                    object = serviceCall(instances, method, value,args);
                }
                if(annotation1 instanceof GetMapping){
                    //get请求
                    GetMapping get = method.getAnnotation(GetMapping.class);
                    String[] value = get.value();
                    object = serviceCall(instances, method, value,args);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return object;
    }


    /**
     * 获取请求地址
     */
    public String getUrl(String[] value){
        String pathUrl = "";
        for (int i = 0; i < value.length; i++) {
            if(value[i].contains("/")){
                pathUrl = value[i];
            }
        }
        return pathUrl;
    }

    /**
     * 服务调用,负载均衡
     */
    public Object serviceCall(List<ServiceInstance> instances,Method method,String[] value,Object[] args){
        RestTemplate restTemplate = beanFactory.getBean(RestTemplate.class);
        Object object = null;
        //获取此注解上请求地址
        String url1 = getUrl(value);
        //获取方法的返回值
        Class<?> returnType = method.getReturnType();
        //筛选出URL
        List<String> urls = instances.stream().map(instance -> instance.getUri().toString() + url1).collect(Collectors.toList());
        //模拟一个负载均衡
        int index = ThreadLocalRandom.current().nextInt(urls.size());

        String url = urls.get(index);

        object = restTemplate.postForObject(url,null,returnType);
        return object;
    }


}
